import { BizUnit, IBizUnitConfig } from '../core';
import { IBaseLayer } from '../core/map/layers';
import logger from 'loglevel';
import { Marker } from 'mapbox-gl';

export class MarkerBizUnit extends BizUnit {
  unitType = 'my-marker'; // 业务单元类型
  private _markers: HTMLElement[] = [];
  private source: any[] = [];

  override async updateGeoData(
    cfg: IBizUnitConfig | null,
    data?: GeoJSON.Feature<GeoJSON.Geometry, GeoJSON.GeoJsonProperties>[],
  ): Promise<void> {
    const features = data || [
      {
        id: 'warning.1',
        coordinates: [116.99088020088942, 36.66424537090326],
        properties: {
          name: '告警点1',
          type: 'warning',
          rt_state: 'normal',
        },
      },
      {
        id: 'warning.2',
        coordinates: [116.97734772649682, 36.65406833434366],
        properties: {
          name: '告警点2',
          type: 'warning',
          rt_state: 'error',
        },
      },
    ];
    this.source = features;
  }

  override async setRenderer(config: IBizUnitConfig): Promise<IBaseLayer[]> {
    logger.info('开始绘制自定义图层');
    // Create layers for custom markers with rounded rectangles
    const layers: IBaseLayer[] = [];
    // demo

    // 添加 marker 到地图
    console.log(this.source, 'source data for markers');
    this.source.forEach((feature) => {
      // 创建自定义 marker 元素
      const markerEl = document.createElement('div');
      markerEl.style =
        'background: linear-gradient(135deg, #ffa7a7ff, #feb47b); width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white;';
      markerEl.textContent = `${feature.properties.name}: ${feature.properties.rt_state}`;
      new Marker(markerEl)
        .setLngLat(feature.coordinates as [number, number])
        .addTo(this.map);
      this._markers.push(markerEl);
    });

    return layers;
  }

  async update() {
    logger.info('更新自定义业务单元');
    // This method can be used to update the markers or any other properties
    // For example, you could refresh the markers based on new data
  }
}
